<!DOCTYPE html>
<html lang="zh" xml:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>客户 - 物联网调试管理系统</title>
    <script th:src="@{/statics/jquery-1.12.4.min.js}"></script>
    <script th:src="@{/statics/tabler/tabler.min.js}"></script>
    <link rel="stylesheet" th:href="@{/statics/tabler/tabler.min.css}">
    <link rel="stylesheet" th:href="@{/statics/layui/layui.css}" />
    <script th:src="@{/statics/layui/layui.js}"></script>
    <link rel="stylesheet" th:href="@{/statics/system/common.css}">
    <script th:src="@{/statics/layer/layer.js}"></script>
    <script th:src="@{/statics/system/common.js}"></script>
</head>
<body>
<div class="page">
    <div th:replace="common/header :: header"></div>

    <div class="page-wrapper">
        <div class="page-header d-print-none">
            <div class="container-xl">
                <div class="row g-2 align-items-center">
                    <div class="col">
                        <!-- Page pre-title -->
                        <div class="page-pretitle">
                            物联网调试管理后台
                        </div>
                        <h2 class="page-title">
                            客户管理
                        </h2>
                    </div>
                    <div class="col-auto ms-auto d-print-none">
                        <div class="btn-list">
                            <button onclick="addCustomer()" class="btn btn-primary d-none d-sm-inline-block">
                                <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"></path><path d="M12 5l0 14"></path><path d="M5 12l14 0"></path></svg>
                                新建客户
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="page-body">
            <div class="container-xl">
                <div class="alert alert-info" role="alert">
                    <div class="text-muted">客户功能仅用于对调试页面进行筛选，无其他实际功能。</div>
                </div>
                <div class="row row-deck row-cards">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="layui-table" id="customer_table" lay-filter="customerTable"></table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>

<!-- 操作列模板 -->
<script type="text/html" id="operateTpl">
    <button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</button>
</script>

<script th:inline="none">
    //菜单class追加属性
    $(function () {
        $("#menu_customers").addClass("active");
    });

    //使用layui表格
    layui.use(['table'], function(){
        var table = layui.table;

        //渲染表格
        table.render({
            elem: '#customer_table',
            url: '/customer/list',
            method: 'GET',
            page: true,
            limit: 10,
            limits: [10, 20, 30, 50],
            cols: [[
                {field: 'id', title: 'ID', width: 80, sort: true, align: 'center'},
                {field: 'name', title: '客户名称', align: 'center', edit: 'text'},
                {field: 'sort', title: '排序', width: 100, sort: true, align: 'center', edit: 'text'},
                {title: '操作', width: 180, align: 'center', toolbar: '#operateTpl'}
            ]],
            parseData: function(res){ //res 即为原始返回的数据
                return {
                    "code": res.code === 200 ? 0 : 1, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.rows //解析数据列表
                };
            },
            request: {
                pageName: 'pageNum',
                limitName: 'pageSize'
            },
            done: function(){
                // 单元格编辑事件
                table.on('edit(customerTable)', function(obj){
                    let update;
                    var field = obj.field; // 得到字段
                    var value = obj.value; // 得到修改后的值
                    var data = obj.data; // 得到所在行所有键值

                    // 值的校验
                    if(value == null || value === ''){
                        layer.msg('值不能为空', {icon: 2});
                        // 还原单元格编辑之前的值
                        update = {};
                        update[field] = obj.oldValue; // 使用旧值
                        obj.update(update);
                        return;
                    }
                    if(field === 'sort'){
                        if(!/^[0-9]*$/.test(value)){
                            layer.msg('排序只能为数字', {icon: 2});
                            // 还原单元格编辑之前的值
                            update = {};
                            update[field] = obj.oldValue; // 使用旧值
                            obj.update(update);
                            return;
                        }
                    }

                    $.ajax({
                        url: '/customer/update',
                        type: 'post',
                        data: JSON.stringify(data),
                        dataType: 'json',
                        contentType: "application/json",
                        success: function(res){
                            if(res.code !== 200){
                                layer.msg(res.msg, {icon: 2});
                                // 还原单元格编辑之前的值
                                update = {};
                                update[field] = obj.oldValue; // 使用旧值
                                obj.update(update);
                            } else {
                                layer.msg('编辑成功', {icon: 1});
                                // 重新加载表格
                                layui.table.reload('customer_table');
                            }
                            console.log(data);
                        }
                    });
                });
            },
        });

        //监听工具条
        table.on('tool(customerTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'edit'){
                editCustomer(data.id);
            } else if(obj.event === 'delete'){
                deleteCustomer(data.id);
            }
        });
    });

    function addCustomer() {
        layer.prompt({title: '请输入客户名称', formType: 0}, function(pass, index){
            if (pass === '' || pass === null || pass === undefined) {
                layer.msg('客户名称不能为空');
                return;
            }
            $.ajax({
                url: '/customer/add',
                type: 'POST',
                contentType:'application/json;charset=UTF-8',
                data: JSON.stringify({
                    name: pass
                }),
                success: function (res) {
                    if (res.code === 200) {
                        layer.msg('添加成功');
                        layui.table.reload('customer_table');
                        layer.close(index)
                    } else {
                        layer.msg(res.msg);
                    }
                },
                error: function (res) {
                    layer.msg('添加失败:' + res.msg);
                }
            })
        });
    }

    function editCustomer(id) {
        layer.prompt({title: '请输入新的客户名称', formType: 0}, function(pass, index){
            $.ajax({
                url: '/customer/update',
                type: 'POST',
                contentType:'application/json;charset=UTF-8',
                data: JSON.stringify({
                    id: id,
                    name: pass
                }),
                success: function (res) {
                    if (res.code === 200) {
                        layer.msg('修改成功');
                        layui.table.reload('customer_table');
                        layer.close(index)
                    } else {
                        layer.msg(res.msg);
                    }
                },
                error: function (res) {
                    layer.msg('修改失败:' + res.msg);
                }
            })
        });
    }

    function deleteCustomer(id) {
        layer.confirm('确定删除 客户ID：' + id + ' ？', {
            btn: ['确定','取消'] //按钮
        }, function(){
            $.ajax({
                url: '/customer/delete/'+id,
                type: 'POST',
                success: function (res) {
                    if (res.code === 200) {
                        layer.msg('删除成功');
                        layui.table.reload('customer_table');
                    } else {
                        layer.msg(res.msg);
                    }
                },
                error: function (res) {
                    layer.msg('删除失败:' + res.msg);
                }
            })
        }, function(){
            layer.closeAll();
        });
    }
</script>
<style>
    .layui-table {
        width: 100%;
    }
    .layui-table-view {
        margin: 10px 0;
    }
</style>
</html>